package top.canyue.word_range_service.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import top.canyue.word_range.exception.DataIsNullException;
import top.canyue.word_range.pojo.dto.PageDTO;
import top.canyue.word_range.pojo.po.WordMapping;
import top.canyue.word_range.pojo.query.WordQuery;
import top.canyue.word_range.pojo.vo.WordMappingVo;
import top.canyue.word_range.result.Result;
import top.canyue.word_range_service.mapper.WordMappingMapper;
import top.canyue.word_range_service.service.WordMappingService;

import java.time.LocalDate;
import java.time.ZoneOffset;
import java.util.Date;

@Service
@RequiredArgsConstructor
public class WordMappingServiceImpl extends ServiceImpl<WordMappingMapper, WordMapping> implements WordMappingService {
    final WordMappingMapper wordMappingMapper;

    @Override
    public PageDTO<WordMappingVo> getWordMappingPage(WordQuery wordQuery){
        // 构造查询条件
        String word = wordQuery.getWord() == null ? "" : wordQuery.getWord();
        String bookId = wordQuery.getBookId() == null ? "" : wordQuery.getBookId();
        Page<WordMapping> page = wordQuery.toMpPageDefaultSortOrderByUpdateTimeDESC();
        Page<WordMapping> wordMapping = lambdaQuery()
                .like(!word.isEmpty(), WordMapping::getWord, word)
                .eq(!bookId.isEmpty(), WordMapping::getBookId, bookId)
                .page(page);
        return PageDTO.of(wordMapping, WordMappingVo.class);


    }

    @Override
    public PageDTO<WordMapping> getAllWordById(WordQuery query) {
        String bookId = query.getBookId() == null ? "" : query.getBookId();
        Page<WordMapping> page = query.toMpPageDefaultSortOrderByRegisterDateASC();
        Page<WordMapping> wordPage = lambdaQuery()
                .eq(WordMapping::getBookId, bookId)
                .page(page);
        return PageDTO.of(wordPage, WordMapping.class);
    }

    @Override
    public Result<WordMappingVo> getRandomWordByDay(){
        Date today = Date.from(LocalDate.now().atStartOfDay().toInstant(ZoneOffset.of("+8")));
        WordMapping wordMapping = wordMappingMapper.getRandomWordByDay(today.getTime());
        if (wordMapping == null){
            throw new DataIsNullException();
        }
        return Result.success(wordMapping.toVo());
    }

}
